package com.igo.onepack.utils;

import java.io.*;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

public class FileUtils {

    private static final char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    private FileUtils() {}

    public static void delete(File file) {
        if (!isValid(file)) return;
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null) return;
            for (File child : files) {
                delete(child);
            }
        }
        file.delete();
    }

    public static boolean isFile(File file) {
        return isValid(file) && file.isFile();
    }

    public static boolean isValid(File file) {
        return file != null && file.exists();
    }

    public static String makeReinforceFile(File parent, String fileName) {
        return parent.getAbsolutePath() + File.separator + makeApkName(fileName,"reinforce");
    }

    public static String makeApkName(String fileName,String suffix) {
        return fileName + "_" + suffix + ".apk";
    }

    public static String makeApkName(File originApkFile, String suffix) {
        return FileUtils.getFileName(originApkFile) + "_"+suffix+".apk";
    }

    public static String getFileName(File file) {
        String name = file.getName();
        return name.substring(0,name.lastIndexOf("."));
    }

    private static boolean isSpace(final String s) {
        if (s == null) return true;
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    private static void ensureParent(File file) {
        File parent = file.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
    }

    public static String getUserTempDir() {
        return System.getProperty("java.io.tmpdir");
    }

    public static void copyResourcesFile(String file, File targetFile) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = FileUtils.class.getClassLoader().getResourceAsStream(file);
            if (is == null) return;
            ensureParent(targetFile);
            os = new FileOutputStream(targetFile);
            org.apache.commons.io.IOUtils.copy(is,os);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
    }

    /**
     * 获取文件的MD5校验码
     *
     * @param filePath 文件路径
     * @return 文件的MD5校验码
     */
    public static byte[] getFileMD5(final String filePath) {
        File file = isSpace(filePath) ? null : new File(filePath);
        return getFileMD5(file);
    }

    /**
     * 获取文件的MD5校验码
     *
     * @param file 文件
     * @return 文件的MD5校验码
     */
    public static String getFileMD5ToString(final File file) {
        return bytes2HexString(getFileMD5(file));
    }

    /**
     * 获取文件的MD5校验码
     *
     * @param file 文件
     * @return 文件的MD5校验码
     */
    public static byte[] getFileMD5(final File file) {
        if (file == null) return null;
        DigestInputStream dis = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            MessageDigest md = MessageDigest.getInstance("MD5");
            dis = new DigestInputStream(fis, md);
            byte[] buffer = new byte[1024 * 256];
            while (true) {
                if (!(dis.read(buffer) > 0)) break;
            }
            md = dis.getMessageDigest();
            return md.digest();
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(dis);
        }
        return null;
    }

    /**
     * byteArr转hexString
     * <p>例如：</p>
     * bytes2HexString(new byte[] { 0, (byte) 0xa8 }) returns 00A8
     *
     * @param bytes 字节数组
     * @return 16进制大写字符串
     */
    private static String bytes2HexString(final byte[] bytes) {
        if (bytes == null) return null;
        int len = bytes.length;
        if (len <= 0) return null;
        char[] ret = new char[len << 1];
        for (int i = 0, j = 0; i < len; i++) {
            ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f];
            ret[j++] = hexDigits[bytes[i] & 0x0f];
        }
        return new String(ret);
    }

}
